import React, { Component } from 'react'
//导入获取所有文章列表的请求方法
import {getArtLists,delArt} from "@api"
//导入antd组件
import {Card,Table,Button,Tag,Tooltip,Modal,message,Breadcrumb} from "antd"
//导入moment解析时间戳
import moment from "moment"
//导入封装好的过滤函数
import {subText} from "@utils/filters"
//引入XLSX
import XLSX from "xlsx"

export default class ArtList extends Component {
  constructor(){
    super();
    this.state={
      exportData:[],
      //默认加载显示，数据请求渲染后消失
      loading:true,
      artLists:[],
      //默认显示第一页
       page:1,
      //默认一页显示10条数据
       count:10,
      //初始总数为0
       total:0,
       //删除的文章的id，默认是-1
       delId:-1,
       //默认不显示弹出提示框
       visible:false,
      columns:[
        {
					title: '标题',
					dataIndex: 'title',
					key: 'title',
				},
				{
					title: '描述',
          render:(text,record,index)=>{
           return(
            <Tooltip title={text.desc}>
            <span> {subText(text.desc,15)}</span>
           </Tooltip>
           )
          },
					key: 'desc',
				},
				{
					title: '作者',
					dataIndex: 'author',
					key: 'author',
				},
				{
					title: '阅读次数',
         render:(text,record,index)=>{
           return (
           <Tag color={text.count>1500&&'red'||text.count<500&&'green' }>{text.count}</Tag>
           )
         },
					key: 'count'
				},
				{
					title: '创建时间',
				 render:(text,record,index)=>{
           return (
             <span>
               {moment(text.createAt).format("YYYY/MM/DD")}
             </span>
           )
         },
					key: 'createAt'
        },
        {
          title:"操作",
          render : (text,row,index)=>{
						return (
							<div> 
								<Button size="small" onClick={()=>{this.props.history.push(`/admin/artEdit/${text.id}`)}} style={{marginRight:10}}>编辑</Button>  
								<Button size="small" onClick={()=>{this.deleteArt(text.id)}} danger>删除</Button>  
							</div>
						)
          },
          key:"action"
        }
      ]
    }
  }
  render() {
    return (
      <div>
       <Modal
					title="删除文章"
					visible={this.state.visible}
					onOk={this.confirmDel}
					onCancel={this.handleCancel}
				>
					您确认删除吗?
				</Modal>
        <Breadcrumb style={{color:"#000",fontSize:"20px",paddingBottom:"10px"}} separator=">">
          <Breadcrumb.Item href="/admin">主页</Breadcrumb.Item>
          <Breadcrumb.Item>文章列表页</Breadcrumb.Item>
         
        </Breadcrumb>
        <Card  extra={<>
                  <Button type="primary" onClick={()=>this.props.history.push("/admin/artAdd")}>增加</Button>
                  <Button style={{marginLeft:"20px"}} onClick={this.exportData}>导出excel</Button>
              </>  }>
						<Table 
							loading={ this.state.loading }
							dataSource={this.state.artLists} 
              columns={this.state.columns} 
              pagination={{
                //一页显示多少条
                pageSize:this.state.count,
                total:this.state.total,
                onChange:(current,pageSize)=>{
									// 点击不同的页数,获取不同页数据,
										this.setState({
											page:current,
											count:pageSize
										},()=>{
											this.getArtLists();
                    })	
								}
              }}
							/>				
				</Card>
      </div>
    )
  }
  componentDidMount(){

    this.getArtLists()
   
  }
  //触发删除文章事件,传参过去
  deleteArt=(id)=>{
    //显示弹出框
    this.setState({
      visible:true,
      delId:id
    })
    
  }
  //取消删除
  handleCancel=()=>{
    this.setState({
      visible:false
    })
  }
  // 确定删除
  confirmDel=()=>{
    //发送请求删除
    delArt(this.state.delId).then(res=>{
      if(res.data.code==="0"){
        message.success(res.data.msg,1,()=>{
					this.props.history.go(0)
				});
      }
    })
    this.setState({
      visible:false
    })
  }
  
  //请求文章列表数据
  getArtLists=()=>{
    getArtLists({page:this.state.page,count:this.state.count}).then(res=>{
      if(res.data.code==="0"){
        this.setState({
          artLists:res.data.data.lists,
          loading:false,
          total:res.data.data.total,
        })
      }
    })
  }
  //导出excel
  exportData=()=>{
    const dataHeaders = ['序号','标题','描述','内容','作者','创建时间','阅读次数'];
		let exportData = [dataHeaders];
    let artLists = this.state.artLists;
    //处理时间
    artLists.forEach((art)=>{
        return art.createAt=moment(art.createAt).format("YYYY/MM/DD")
    })
    // //处理富文本
    // artLists.forEach((art)=>{
    //   return art.content=art.content
    // })
		artLists.forEach(art=>{
      //console.log(Object.values(art))

			exportData.push(Object.values(art))
		})
		// // 导出为excel
		const ws = XLSX.utils.aoa_to_sheet(exportData);
		const wb = XLSX.utils.book_new();
		XLSX.utils.book_append_sheet(wb, ws, "SheetJS");
				/* generate XLSX file and send to client */
		XLSX.writeFile(wb, "文章.xlsx")
  }
}
